//
//  NDCalculatorView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/25.
//


import SwiftUI

struct NDCalculatorView: View {
    // 计算器数据模型
    @State private var loanAmount: String = ""
    @State private var loanTerm: String = ""
    
    @StateObject private var viewModel = NDCalculatorViewModel()
    @State private var showRateTypePicker = false
    @State private var rateTypeString: String?
    
    @State private var showRatePicker = false
    @State private var selectedInterestRate: Float?
    
    @State private var selectedIndex: Int? = 0
    let rates: [NDCalculatorRateType] = [.low, .middle, .high]
    var selectedRateType: NDCalculatorRateType? {
        guard let index = selectedIndex, index < rates.count else {
            return nil
        }
        return rates[index]
    }
    
    let firstTop = 30.0
    
    var body: some View {
        let baseConfig = NDBaseConfig(
            backgroundImgName: "Information background",
            backgroundColor: .clear,
            showNavigationBar: true,
            hiddenTabbar: false
        )
        let navigationConfig = NavigationConfig(
            title: "Calculator",
            showSystemBackButton: false
        )
        
        NDBaseContentView(
            baseConfig: baseConfig,
            navigationConfig: navigationConfig
        ) {
            ScrollView {
                ZStack(alignment: .top) {
                    HStack {
                        titleImage
                        Spacer()
                        iconImage
                    }
                    .padding(.horizontal, 16)
                    .padding(.top, firstTop + topSafeArea)
                    
                    // 计算器主体
                    VStack(spacing: 25) {
                        calculateContentView
                        resultContentView
                        Spacer()
                    }
                    .padding(.horizontal, 16)
                    .padding(.top, firstTop + 116 + topSafeArea)
                    
                    // 连接线 - 覆盖在两个视图之上
                    VStack(alignment: .leading, spacing: 0) {
                        calculateContentView
                            .opacity(0)
                        connectLineImage
                        Spacer()
                    }
                    .padding(.top, firstTop + 49 + topSafeArea)
                    .padding(.horizontal, 26)
                    .hidden(!viewModel.showResult)
                }
            }
            .padding(.bottom, 70)
        }
        .ignoresSafeArea(.all)
        .ignoresSafeArea(.keyboard, edges: .bottom)
        .onChange(of: viewModel.isLoading) { isLoading in
            DispatchQueue.main.async {
                if isLoading {
                    NDProgressHUD.show()
                } else {
                    NDProgressHUD.dismiss()
                }
            }
        }
        .onChange(of: viewModel.errorMessage) { msg in
            NDProgressHUD.showInfo(msg)
        }
        .ndCustomPopupOnWindow(isPresented: $showRateTypePicker,
                               style: .actionSheet) {
            NDCalRateEnumView(
                title: "Interest rate type",
                dataSource: [LoanDurationType.month.title, LoanDurationType.year.title],
                onSelectionChanged: { index, item in
                    print("选择了第\(index)项: ")
                },
                onConfirmAction: { item in
                    print("确认选择: ")
                    showRateTypePicker = false
                    if let item = item {
                        rateTypeString = item
                    }
                },
                onCloseAction: {
                    showRateTypePicker = false
                }
            )
            .padding(.horizontal, 5)
            .background(Color(hex: "#FFFFFF"))
        }
                               .ndCustomPopupOnWindow(isPresented: $showRatePicker,
                                                      style: .actionSheet) {
                                   NDCalRateEnumView(
                                       title: "Interest rate",
                                       dataSource: [0.02, 0.03, 0.04],
                                       onSelectionChanged: { index, item in
   
                                       },
                                       onConfirmAction: { item in
                                           showRatePicker = false
                                           if let item = item {
                                               selectedInterestRate = Float(item)
                                           }
                                       },
                                       onCloseAction: {
                                           showRatePicker = false
                                       }
                                   )
                                   .padding(.horizontal, 5)
                                   .background(Color(hex: "#FFFFFF"))
                               }
    }
    
    // 计算逻辑
    private func calculate() {
        UIApplication.shared.endEditing()
        guard let amount = Int(loanAmount),
              let term = Int(loanTerm),
              term > 0,
              let rateTypeString = rateTypeString,
              !rateTypeString.isEmpty,
              let selectedInterestRate = selectedInterestRate else {
            viewModel.showResult = false
            return
        }
        
        
        let type = LoanDurationType(str: rateTypeString) ?? .month
        viewModel.requestCalculatorResult(loanAmount: amount,
                                          loanTerm: term,
                                          rate: selectedInterestRate,
                                          type: type)
    }
    
    // 背景图片
    private var titleImage: some View {
        Image("calculator_name")
            .scaledToFit()
            .frame(height: 29)
    }
    
    private var iconImage: some View {
        Image("illustration")
            .scaledToFit()
            .frame(height: 150)
    }
    
    private var connectLineImage: some View {
        Image("connecting_line")
            .scaledToFit()
            .frame(height: 150)
    }
}

extension NDCalculatorView {
    var calculateContentView: some View {
        // 计算器表单
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text(localizedString("calcu_Loan_amount"))
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))

                TextField("Enter the loan amount", text: $loanAmount)
                    .padding(8)
                    .frame(height: 48)
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#999999"))
                    .background(Color(hex: "#F7F8F9"))
                    .cornerRadius(8)
                    .keyboardType(.numberPad)
            }

            VStack(alignment: .leading, spacing: 8) {
                Text("Loan term")
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#666666"))
                TextField("Enter the loan term", text: $loanTerm)
                    .padding(8)
                    .frame(height: 48)
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#999999"))
                    .background(Color(hex: "#F7F8F9"))
                    .cornerRadius(8)
                    .keyboardType(.numberPad)
            }
            
            NDCommonActionItem(
                title: "Interest rate type",
                textContent:  Binding(
                    get: { rateTypeString ?? "" },
                    set: { rateTypeString = $0 }
                ),
                actionType: .button,
                plactHolder: "Please select",
                keboardType: .default,
                fieldId: 0,
                onBeginEditing: { fieldId in
                },
                onEndEditing: {

                },
                onClickButton: {
                    endEditing()
                    showRateTypePicker = true
                }
            )
            
            NDCommonActionItem(
                title: "Interest rate",
                textContent: Binding(
                    get: { selectedInterestRate == nil ? "" : String(selectedInterestRate ?? 0) },
                    set: { selectedInterestRate = Float($0) }
                ),
                actionType: .button,
                plactHolder: "Please select",
                keboardType: .default,
                fieldId: 0,
                onBeginEditing: { fieldId in
                },
                onEndEditing: {

                },
                onClickButton: {
                    endEditing()
                    showRatePicker = true
                }
            )

            // 计算按钮
            Button(action: calculate) {
                Text("Calculate")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.black)
                    .clipShape(Capsule())
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 24)
        .background(Color(hex: "#FFFFFF"))
        .cornerRadius(20)
        .overlay(
            RoundedRectangle(cornerRadius: 20)
                .stroke(Color(hex: "#271F24"), lineWidth: 1)
        )
    }
}

extension NDCalculatorView {
    var resultContentView: some View {
        Group {
            ZStack {
                backgroundGradient
                
                VStack(alignment: .leading, spacing: 12) {
                    HStack {
                        Text("Principal")
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#666666"))
                        Spacer()
                        Text("\(viewModel.principal)")
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(Color(hex: "#271F24"))
                    }
                    
                    HStack {
                        Text("Interest amount")
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#666666"))
                        Spacer()
                        Text(viewModel.displayInterestAmount)
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(Color(hex: "#271F24"))
                    }
                    
                    HStack {
                        Text("Total amount")
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#666666"))
                        Spacer()
                        Text(viewModel.displayTotalAmount)
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(Color(hex: "#271F24"))
                    }
                }
                .padding(16)
            }
            .frame(maxWidth: .infinity)
            .frame(height: 135)
            .cornerRadius(20)
            .overlay(
                RoundedRectangle(cornerRadius: 20)
                    .stroke(Color(hex: "#271F24"), lineWidth: 1)
            )
            .rotationEffect(.degrees(3))
            .hidden(!viewModel.showResult)
        }
    }
    
    private var backgroundGradient: some View {
        LinearGradient(
            gradient: Gradient(stops: [
                Gradient.Stop(color: Color(hex: "#FFE6DD"), location: 0.0),
                Gradient.Stop(color: Color(hex: "#FFF0EB"), location: 0.4),
                Gradient.Stop(color: Color(hex: "#FFFFFF"), location: 0.5)
            ]),
            startPoint: .top,
            endPoint: .bottom
        )
    }
}

#Preview {
    NDCalculatorView()
}
